<?php

/**
 * 跑步相关接口
 */
class runController extends base
{

    public function __construct()
    {
      parent::__construct();
    }

    //跑步设置目标的类型
    static $targetType = array('mileage','elapsedtime','calorie');
    /**
     * 上传用户单次跑步数据
     */
    public function dorunningData()
    {
        $mileage = common::request('mileage', 'P');
        $elapsedtime = common::request('elapsedtime', 'P');
        $calorie = common::request('calorie', 'P',0);
        $city = common::request('city', 'P');
        $coordinate = common::request('coordinate', 'P');
        $point_coordinate = common::request('point_coordinate', 'P');
        $updatetime = intval(common::request('updatetime', 'P')); //跑步提交时间
        $order_id = common::request('order', 'P'); //排序

        $target_type = common::request('target_type', 'P', ''); //跑步设定的目标类型
        $target_rate = common::request('target_rate', 'P', ''); //该次跑步目标完成度
        $run_mood = common::request('run_mood', 'P', ''); //该次跑步的心情
        $expression_id = intval(common::request('expression_id', 'P', '')); //该次跑步的心情图标id
        $detail_speed = common::request('detail_speed', 'P', ''); //该次跑步配速
        $five_time = common::request('five_time', 'P', '0'); //当次跑步5公里最短用时（min）
        $ten_time = common::request('ten_time', 'P', '0'); //当次跑步10公里最短用时（min）
        $half_mtime = common::request('half_mtime', 'P', '0'); //当次跑步 半马最短用时（min）
        $mara_time = common::request('mara_time', 'P', '0'); //当次跑步 全马最短用时（min）
        $medal = common::request('medal', 'P', '[]'); //该次跑步获得的勋章
        $recordImgCount = common::request('recordImgCount', 'P', ''); //图片总数量
        $southWestPoint = common::request('southWestPoint', 'P', ''); //跑步坐标西南极值
        $northEastPoint = common::request('northEastPoint', 'P', ''); //跑步坐标东北极值
        $qq_acc_token = common::request('qq_acc_token', 'P', ''); //用户access_token (QQ健康中心)
        $qq_openid = common::request('qq_openid', 'P', ''); //用户openid (QQ健康中心)
        $max_did = common::request('max_did', 'P', 0); //客户端当年跑步记录中最大的did
        $overSpeed = common::request('overSpeed', 'P', 0); // 异常跑步数据类型

        // 2.8.2 及以上版本使用
        $detail_speed_curve = common::request('detail_speed_curve', 'P');
        $detail_elevation = common::request('detail_elevation', 'P');
        $detail_elevation_curve = common::request('detail_elevation_curve', 'P');
        $detail_elevation_fold = common::request('detail_elevation_fold', 'P');
        $detail_footsteps = common::request('detail_footsteps', 'P');
        $detail_footsteps_curve = common::request('detail_footsteps_curve', 'P');
        $detail_footsteps_fold = common::request('detail_footsteps_fold', 'P');
        $detail_stride = common::request('detail_stride', 'P');
        $tipsString = common::request('tipsString','P','');
        $gearId = common::request('gearId', 'P');    //跑鞋ID，2.8.7新增
        $tmp_run_days = common::request('tmp_run_days', 'P');

        // 用户是否已上传过该条跑步记录(order_id)
        $isHaveRunData = FALSE;

        // 2.8.3及以上版本将不再返回多余字段
        $isFix2830 = $this->vn >= 2830;

        if($this->vn >= 1100) //版本：1.1.0
        {
          if(empty($detail_speed))
          {
            $_ENV['error']->getErrors(101);
            exit();
          }
          $target_type = !empty($target_type) && in_array($target_type, self::$targetType) ? $target_type : '';
          $target_rate = !empty($target_type) && !empty($target_rate) ? $target_rate : 0;
        }
        else
        {
            $target_type = $target_rate = $run_mood = $detail_speed = '';
        }

        if ($mileage && $elapsedtime && is_numeric($mileage) && is_numeric($elapsedtime) && intval($order_id))
        {

            $record_img = array();
            $coordinate = str_replace(' ', '', $coordinate);
            $coordinate = str_replace('\n', '', $coordinate);
            $coordinate = str_replace('\\', '', $coordinate);
            $coordinate = base64_encode(gzcompress($coordinate, 9));

            $medal = str_replace(' ', '', $medal);
            $medal = str_replace('\n', '', $medal);
            $medal = str_replace('\\', '', $medal);
            $uid = $this->uid;
            $run_mod = $this->load('run');

            if($uid)
            {
              $redis_key = REDIS_PREFIX . 'runDataOrder_' . $uid;
              // if ($this->redis->hexists($redis_key, $order_id))

              $runInfo = $this->db->getRow("select did,updatetime from r_data where uid='{$uid}' and order_id='{$order_id}' limit 1");

              if($runInfo)
              {
                $did = intval($runInfo['did']);

                if($this->vn <= 1500)
                {
                  $old_updatetime = $runInfo['updatetime'];
                  empty($old_updatetime) && $old_updatetime = 0;
                  if($old_updatetime && abs($old_updatetime-$updatetime) < 3600)
                  {
                    $isHaveRunData = TRUE;
                    $this->result['result']['did'] = $did;

                    if(!$isFix2830)
                    {
                      $_ENV['error']->getErrors(308);
                      exit();
                    }
                  }
                  else
                  {
                    $old_order = $order_id;
                    $order_id = $updatetime;
                  }
                }
                else
                {
                  $isHaveRunData = TRUE;
                  $this->result['result']['did'] = $did;

                  if(!$isFix2830)
                    {
                      $_ENV['error']->getErrors(308);
                      exit();
                    }
                }
              }
            }
            else
            {
              $redis_key = REDIS_PREFIX .'runDataVOrder_' . $this->vid;
              if ($this->redis->hexists($redis_key, $order_id))
              {
                  $did = $this->db->getOne("select did from r_visitor_data where vid='{$this->vid}' and updatetime='{$updatetime}' limit 1");
                  if(!$did){
                    $_ENV['error']->getErrors(308);
                    exit();
                  }
                  $isHaveRunData = true;
              }
            }

            if(!$isHaveRunData)
            {
                if(($this->vn >= 1600 && $this->projectId == 2) || $this->vn >= 1800)
                {
                    $record_img = common::request('record_img', 'P', '[]');
                }
                else
                {
                    require FILE . 'lib/image.class.php';
                    for($i = 0; $i <= 4; $i++)
                    {
                      $i = $i==0 ? '' : $i;
                      if (!empty($_FILES['record_img'.$i])) //跑步记录图片
                      {
                          $loadImg = $run_mod->uploadRecordImg('record_img'.$i);
                          $loadImg && $record_img[] = $loadImg;
                      }
                    }
                    $record_img = json_encode($record_img);
                }

                !$overSpeed && $overSpeed = $run_mod->checkCheatRun($uid,$mileage,$elapsedtime,$updatetime,$detail_speed);
                if($overSpeed)
                {
                    $medal = [];
                }

                $runData = compact('mileage','elapsedtime','calorie','city','coordinate','point_coordinate','record_img','updatetime','order_id','target_type','target_rate','run_mood','expression_id','detail_speed','recordImgCount','southWestPoint','northEastPoint','medal','five_time','ten_time','half_mtime','mara_time', 'overSpeed', 'detail_speed_curve', 'detail_elevation', 'detail_elevation_curve', 'detail_elevation_fold', 'detail_footsteps', 'detail_footsteps_curve', 'detail_footsteps_fold', 'detail_stride', 'tipsString', 'gearId', 'tmp_run_days');
                $did = $run_mod->uploadUserRunData($runData);
                
                if($uid && $did && $overSpeed == 0){
                    //其他异步
                    $run_mod->pushPendingRunList($did);
                }
              
                //上传跑步数据成功后，更新跑鞋里程
                if($uid && $did && $gearId && $overSpeed == 0)
                {
                    //获取跑鞋的具体信息(为拿到之前的里程数据)
                    $gearInfo = $this->db->getRow("select * from r_gear_comment where gearId = {$gearId} and uid = {$uid}");
                    $mileageNew = $gearInfo['mileage'] + $mileage;
                    //更新数据
                    $this->load('gear')->setGearMileage($gearId, $mileageNew, $uid);
                }
                
            }
            $result['order_id'] = $order_id;
            $result['is_success'] = $did > 0 ? 1 : 0;
            $result['run_data'] =  $did > 0 ? $this->load('run')->getRunDataByDid($did) : array();
            $result['overSpeed'] = isset($result['run_data']['overSpeed']) ? $result['run_data']['overSpeed'] : $overSpeed;
            $result['history_dids'] = $this->load('run')->getRangeRunDids($max_did, $did);
            isset($old_order) && $result['run_data']['order_id'] = $old_order;

            if($isFix2830 && $result['run_data'])
            {
                $tmp = $result['run_data'];
                $result['run_data'] = [];
                $result['run_data']['did'] = $tmp['did'];
                $result['run_data']['order_id'] = $tmp['order_id'];
                $result['run_data']['overSpeed'] = $tmp['overSpeed'];
            }

            $this->result['result'] = $result;
        } else
        {
            $_ENV['error']->getErrors(101);
        }
    }
    /**
     * 批量上传用户跑步数据
     */
    public function dobatchUploadRunData()
    {

        $max_did = common::request('max_did', 'P', 0);
        $runData = common::request('runData', 'P');
 
        $uid = $this->uid;
        $runData = str_replace(' ', '', $runData);
        $runData = str_replace('\n', '', $runData);
        $runData = json_decode($runData, true);

        if(empty($uid) || empty($runData))
        {
          $_ENV['error']->getErrors(101);
          exit;
        }
       
        $relMaxDid = 0;
        $data = array();
        $qqHealthData = array();

        foreach ($runData as $value)
        {
          $did = 0;
          $result = array();
          $value['order_id'] = $value['order'];
         
          if (isset($value['mileage']) && isset($value['elapsedtime']) && isset($value['order_id']) && isset($value['coordinate']) && $value['mileage'] && $value['elapsedtime'] && is_numeric($value['mileage']) && is_numeric($value['elapsedtime']) && intval($value['order_id']))
          {

              unset($value['order']);
              
              is_array($value['detail_speed']) && $value['detail_speed'] = json_encode($value['detail_speed']);
              is_array($value['southWestPoint']) && $value['southWestPoint'] = json_encode($value['southWestPoint']);
              is_array($value['northEastPoint']) && $value['northEastPoint'] = json_encode($value['northEastPoint']);
              isset($value['record_img']) && is_array($value['record_img']) && $value['record_img'] = @json_encode($value['record_img']);
              isset($value['point_coordinate']) && is_array($value['point_coordinate']) && $value['point_coordinate'] = json_encode($value['point_coordinate']);
              isset($value['medal']) && is_array($value['medal']) && $value['medal'] = json_encode($value['medal']);

              is_array($value['coordinate']) && $value['coordinate'] = json_encode($value['coordinate']);
              $coordinate = str_replace(' ', '', $value['coordinate']);
              $coordinate = str_replace('\n', '', $coordinate);
              $coordinate = str_replace('\\', '', $coordinate);
              $value['coordinate'] = base64_encode(gzcompress($coordinate, 9));
   
              $order_id = $value['order_id'];
               
              $did = $this->db->getone("select did from r_data where uid = '{$uid}' and order_id = '{$order_id}' limit 1");
              
              if(!$did)
              {
                $qq_openid = isset($value['qq_openid']) ? $value['qq_openid'] : '';
                $qq_acc_token = isset($value['qq_acc_token']) ? $value['qq_acc_token'] : '';
                unset($value['qq_openid'], $value['qq_acc_token'], $value['max_did']);
               

                $value['overSpeed'] = $this->load('run')->checkCheatRun($uid,$value['mileage'],$value['elapsedtime'],$value['updatetime'],$value['detail_speed']);
               if($value['overSpeed'])
                {
                  $value['medal'] = [];
                }

                $did = $this->load('run')->uploadUserRunData($value);
                $this->load('run')->pushPendingRunList($did);
              }
          }
          
          $result['order_id'] = $value['order_id'];
          $result['overSpeed'] = isset($value['overSpeed'])? $value['overSpeed'] : 0;
          $result['is_success'] = $did > 0 ? 1 : 0;
          $result['run_data'] =  $did > 0 ? $this->load('run')->getRunDataByDid($did) : null;
          $data[] = $result;
          $relMaxDid = ($relMaxDid > 0 && $relMaxDid > $did) ? $did : $relMaxDid;
        }
        $history_dids = $this->load('run')->getRangeRunDids($max_did, $relMaxDid);
        $this->result["result"] = compact('data', 'history_dids');

    }
    /**
     * 删除用户单次跑步数据
     */
    public function doDelRunningData()
    {
        $order_id = intval(common::request('order', 'P'));
        if(empty($order_id) || $order_id <= 0)
        {
            $_ENV['error']->getErrors(101);
        }
        else
        {
          $rel = $this->load('run')->deleteUserRunData($order_id);

          $is_success = $rel['is_success'];
          $uid = $this->uid;
          if($is_success && $this->uid)
          {
              // 群组跑步数据
              $this->load('group')->deleteRunData($this->uid,array('did' => $rel['did'], 'updatetime' => $rel['updatetime']));

              //获取该条记录对应的跑鞋id
              $gearId = $this->db->getOne("select gearId from r_data where did = '{$rel['did']}'");
              //重置跑鞋里程
              if($gearId){
                  $this->db->update("update r_gear_comment set mileage = mileage - '{$rel['mileage']}' where gearId = {$gearId} and uid = {$uid}");
              }
          }
          $result['order_id'] = $order_id;
          $result['is_success'] = $is_success;

          $this->result['result'] = $result;
        }
    }
    /**
     * 批量删除用户跑步数据
     */
    public function dobatchDelRunData()
    {
        $result = array();
        $order_ids = common::request('order_ids', 'P');
        if(empty($order_ids) || json_decode($order_ids, true) === false || !is_array(json_decode($order_ids, true)))
        {
            $_ENV['error']->getErrors(101);
        }
        else
        {
          $order_ids = json_decode($order_ids, true);
          if(empty($order_ids))
          {
            $result = array();
          }
          else
          {
            foreach ($order_ids as $key => $order_id) {
              $rel = $this->load('run')->deleteUserRunData($order_id);
              $is_success = $rel['is_success'];
              if($is_success)
              {
                  // 群组跑步数据
                  $this->load('group')->deleteRunData($this->uid,array('did' => $rel['did'], 'updatetime' => $rel['updatetime']));

                  //获取该条记录对应的跑鞋id
                  $gearId = $this->db->getOne("select gearId from r_data where did = '{$rel['did']}'");
                  //重置跑鞋里程
                  if($gearId){
                      $this->db->update("update r_gear_comment set mileage = mileage - '{$rel['mileage']}' where gearId = {$gearId} and uid = {$uid}");
                  }
              }
              $result[] = compact('order_id', 'is_success');
            }
          }
        }
        $this->result['result'] = $result;
    }
    /**
     * 上传用户分享图片
     */
    public function dorunningShare()
    {
        $did = common::request('did', 'P');
        if ($did && is_numeric($did) && !empty($_FILES['share_img']))
        {
            $share_img = $this->load('run')->uploadShareImg('share_img');
            $result = $this->load('run')->saveShareImg($did, $share_img);
            if ($result)
            {
                $this->result['result'] = array(
                    'did' => $did,
                    'share_img' => $share_img
                );
            } else
            {
                $_ENV['error']->getErrors(701);
            }
        } else
        {
            $_ENV['error']->getErrors(101);
        }
    }

    /**
     * 获取用户跑步历史数据
     */
    public function dohistory()
    {
        $page = common::request('page', 'G', 1);
        $did = common::request('did', 'G', 0);
        $direc = common::request('direc', 'G', 'next');
        $offset = common::request('offset', 'G', 20);
        $this->vn < 1800 && $offset = 100;
        $did < 0 && $did = 0;
        if($this->uid)
        {
          $data = $this->load('run')->getClientRunHistoryData($this->uid, $page, $did, $direc, $offset);
          // 获取total信息
          $elapsedtime = 0;
          $mileage = 0.00;
          $calorie = 0;
          $total_rate = 0;
          if(empty($did))
          {
            $userInfo = $_ENV['client']->getUserInfo($this->uid);

            $elapsedtime = intval($userInfo['total_elapsedtime']);
            $mileage = round($userInfo['total_mileage'], 2);
            $calorie = intval($userInfo['total_calorie']);
            $total_rate = intval($userInfo['total_rate']);
          }
          elseif($direc == 'prev')
          {
            // 当客房端获取新记录时， 计算本跑步记录统计数据
            if($data)
            {
              foreach ($data as $value)
              {
                // 只统计正常数据
                if($value['overSpeed'] == 0)
                {
                  $elapsedtime += intval($value['elapsedtime']);
                  $mileage += round($value['mileage'],3);
                  $calorie += intval($value['calorie']);
                  $total_rate += 1;
                }
              }
            }
          }
          $timeLine = $this->time;
          $total = compact('elapsedtime', 'mileage', 'calorie', 'total_rate');

          $this->result['result'] = array('total' => $total, 'timeLine' => $timeLine, 'data' => $data);
       }
       else
       {
          $vid = $this->vid;
          $old_uid = $this->db->getOne("select old_uid from r_visitor where vid ='{$vid}'");
          if($this->vn < '1100' || $old_uid > 1) //1.0版本返回数据
          {
            $this->result['result'] = $this->load('run')->getVisitorRunHistoryData($vid, $page);
          }
          else
          {
            $this->result['result'] = array('total' => (object) array(), 'data' => array());
          }
       }
    }
    /**
     * 获取用户跑步历史数据（结果按照月份分组）
     */
    public function dohistoryGroupMonth()
    {
        $did = common::request('did', 'G', 0);
        $direc = common::request('direc', 'G', 'prev');
        $offset = common::request('offset', 'G', 20);
       if($this->uid)
       {
          $data = array();
          $runData = $this->load('run')->getClientRunHistoryData($this->uid, 1, $did, $direc, $offset);
          // 获取total信息
          $elapsedtime = 0;
          $mileage = 0.00;
          $calorie = 0;
          $total_rate = 0;
          if(empty($did))
          {
            $elapsedtime = intval($this->userInfo['total_elapsedtime']);
            $mileage = round($this->userInfo['total_mileage'], 2);
            $calorie = intval($this->userInfo['total_calorie']);
            $total_rate = intval($this->userInfo['total_rate']);
          }
          elseif($direc == 'prev')
          {
            if($runData)
            {
              foreach ($runData as $value) {
                $elapsedtime += intval($value['elapsedtime']);
                $mileage += round($value['mileage'],3);
                $calorie += intval($value['calorie']);
                $total_rate += 1;
              }
            }
          }
          $total = compact('elapsedtime', 'mileage', 'calorie', 'total_rate');
          // 将跑步记录按照月份分组
          if($runData)
          {
            foreach ($runData as $v) {
              $month = date("Ym", $v['updatetime']);
              $data[$month][] = $v;
            }
          }
          $this->result['result'] = array('total' => $total, 'data' => $data);
       }
       else
       {
          $this->result['result'] = array('total' => array(), 'data' => array());
       }
    }
    /**
     * 修改用户跑步记录
     */
    public function domodifyMyRunData()
    {
        $did = common::request('did', 'P', 0);
        $record_img = common::request('record_img', 'P', '[]');
        $recordImgCount = common::request('recordImgCount', 'P', 0);
        $run_mood = common::request('run_mood', 'P', '');
        $expression_id = common::request('expression_id', 'P', 0);

        $this->result['result']['is_success'] = $this->load('run')->modifyRunData($this->uid, $did, $record_img, $recordImgCount, $run_mood, $expression_id);
    }
    /**
     * 获取用户跑步统计数据（月）
     */
    public function dostats()
    {
        $month = common::request('val');
        $month && $month = strtotime($month);

        $this->result['result'] = $this->load('run')->getClientRunDataStats($this->uid, $month);
    }

    /**
     * 获取排行榜数据
     */
    public function dostandings()
    {
        $this->result['result'] = $this->load('run')->getMileageStandings();
    }
    /**
     * 根据did获取跑步数据
     */
    public function dogetHistoryByDids()
    {
        $uid = $this->uid;
        if(empty($uid))
        {
          $_ENV['error']->getErrors(101);
          exit();
        }
        $dids = common::request('dids', 'G');
        $data = $this->load('run')->getBatchRunDataByDid($uid, $dids);
        $elapsedtime = 0;
        $mileage = 0.00;
        $calorie = 0;
        $total_rate = 0;
        if($data)
        {
          foreach ($data as $value) {
            $elapsedtime += intval($value['elapsedtime']);
            $mileage += round($value['mileage'],3);
            $calorie += intval($value['calorie']);
            $total_rate += 1;
          }
        }
        $total = compact('elapsedtime', 'mileage', 'calorie', 'total_rate');
        $this->result['result'] = compact('total', 'data');
    }
    /**
     * 用户跑步数据统计信息
    */
    public function dorunDataStatistics()
    {
        $uid = $this->uid;
        if(empty($uid))
        {
          $_ENV['error']->getErrors(201);
          exit();
        }
       $this->result['result'] = $this->load('run')->getRunStatistics($uid);
    }
    /**
     * 群组跑步记录点赞
    */
    public function dolikeRunReCord()
    {
        $did = common::request('did', 'G');
        $gid = common::request('gid', 'G', 0);
        $uid = $this->uid;
        if(empty($uid))
        {
          $_ENV['error']->getErrors(201);
          exit();
        }
        $gInfo = $this->load('group')->getGroupInfo($gid);
        if(empty($gInfo) || (isset($gInfo['isDismiss']) && $gInfo['isDismiss'] == 1))
        {
            $_ENV['error']->getErrors(905);
            exit;
        }
        $role = $this->load('group')->getGroupRole($gid, $uid);
        if($role == -1 || $role == 3)
        {
           $_ENV['error']->getErrors(903);
            exit;
        }
        $this->load('run')->likeRunRecord($uid, $did, $gid);
        $likes = $this->load('run')->getRunRecordLikes($did, $gid);
        $this->result['result']['likes'] = $likes;
        $this->breakCall();
        if($likes == 1)
        {
            $runData = $this->db->getRow("select uid,mileage from r_data where did = '{$did}'");
            $runData['mileage'] = round($runData['mileage'], 2);
            $nickname = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'nickname');
            $data = array('title'   => sprintf("你刚刚跑了%s公里，%s觉得很赞！", $runData['mileage'], $nickname),
                          'text'    => '',
                          'body'    => sprintf("你刚刚跑了%s公里，%s觉得很赞！", $runData['mileage'], $nickname),
                          'url'    => 'joggers://groupRecord/'.$gid
                        );
            $this->load('push')->pushNoticeByUid(array($runData['uid']), $data);
        }
    }
    /**
     * 跑步日志上传
    */
    public function dolog()
    {
        $num = common::request('num', 'P');
        $key = common::request('key', 'P');
        $is_success = $this->load('run')->saveLog($num, $key,'log') ? 1 : 0;
        $this->result['result']['is_success'] = $is_success;
    }
    /**
     * 用户变更的跑步记录
    */
    public function domodifyHistory()
    {
        $timeLine = common::request('timeLine', 'G');
        $timeLine = intval($timeLine);

        $uid = $this->uid;

        $total = array();
        $modify_time = $this->time;
        $add = array();
        $modify = array();
        $delete = array();
        
        if($uid && preg_match('/14[0-9]{8}/', $timeLine))
        {
            $this->load('run')->refreshUserRunRecord($uid);
            $userInfo = $_ENV['client']->getUserInfo($uid);

            $elapsedtime = intval($userInfo['total_elapsedtime']);
            $mileage = round($userInfo['total_mileage'], 2);
            $calorie = intval($userInfo['total_calorie']);
            $total_rate = intval($userInfo['total_rate']);

            $total = compact('elapsedtime', 'mileage', 'calorie', 'total_rate');

            $add = $this->load('run')->getUserModifyRun($uid, 'add', $timeLine);
         
            foreach ($add as $key => $value) {
              $add[$key]["month"] = date("Ym",$value["updatetime"]);
            }

          
            $modify = $this->load('run')->getUserModifyRun($uid, 'modify', $timeLine);
            $delete = $this->load('run')->getUserModifyRun($uid, 'delete', $timeLine);
        }

        $this->result['result'] = compact('total', 'modify_time', 'add', 'modify', 'delete');

    }

    // 获取用户某年内按月分组的的跑步记录
    public function doyearHistory()
    {
        $year = intval(common::request('year'));
        !$year && $year = date('Y');
        $page = intval(common::request('page','G',1));
        $offset = intval(common::request('offset','G',2000));
        $did = intval(common::request('did','G',0));

        if($this->uid)
        {
            //$data = $this->load('run')->getClientRunHistoryData($this->uid, $page, $did, 'next', $offset);
            $data = $this->load('run')->getClientRunData($this->uid, $page, $did, 'next', $offset);
        }
        else
        {
            //$data = $this->load('run')->getVisitorRunHistoryData($this->vid, $page, $offset);
            $data = $this->load('run')->getVisitorRunData($this->vid, $page, $offset);
        }

        if($data)
        {
            $tmp = $data;
            $data = [];

            foreach($tmp as $k => $runData)
            {
                $dateYear = date('Y', $runData['updatetime']);

                if($dateYear != $year)
                {
                    continue;
                }

                $ym = date('Ym', $runData['updatetime']);
                $data[$ym]['title'] = date('Y年n月', $runData['updatetime']);
                $data[$ym]['data'][] = [
                    'did' => $runData['did'],
                    'order_id' => $runData['order_id'],
                    'mileage' => $runData['mileage'],
                    'elapsedtime' => $runData['elapsedtime'],
                    'calorie' => $runData['calorie'],
                    'updatetime' => $runData['updatetime'],
                ];
            }

            $data = array_values($data);
        }

        $this->result['result'] = $data ? $data : [];
    }

    // 个人周目标（公里）设置接口
    public function dotargetByWeek()
    {
        $mileage = intval(common::request('mileage', 'P'));

        if($this->uid && $mileage > 0 && $mileage <= 3000)
        {
            $targetKey = date('YW');
            $targetType = 'week';
            $status = $this->load('run')->setUserSelfTarget($this->uid, $targetKey, $mileage, $targetType);
            $this->result['result']['status'] = $status ? 1 : 0;
        }
        else
        {
            $this->result['result']['status'] = 0;
        }
    }

    // 个人月目标（公里）设置接口
    public function dotargetByMonth()
    {
        $mileage = intval(common::request('mileage', 'P'));

        if($this->uid && $mileage > 0 && $mileage <= 3000)
        {
            $targetKey = date('Ym');
            $targetType = 'month';
            $status = $this->load('run')->setUserSelfTarget($this->uid, $targetKey, $mileage, $targetType);
            $this->result['result']['status'] = $status ? 1 : 0;
        }
        else
        {
            $this->result['result']['status'] = 0;
        }
    }

    // 个人按周汇总的跑步里程数据列表接口
    public function dorunDataByWeek()
    {
        if(!$this->uid)
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        else
        {
            $yw = intval(common::request('yw'));

            $maxYw = date('YW');
            (!$yw || strlen($yw) != 6) && $yw = $maxYw;
            $yw < 201408 && $yw = 201408;

            $maxDays = $this->redis->zrangebyscore(REDIS_PREFIX . 'Weeks', $yw, '+inf', ['withscores' => TRUE, 'limit' => [1, 1]]);
            $ywDays = $this->redis->zrevrangebyscore(REDIS_PREFIX . 'Weeks', $yw, '-inf', ['withscores' => TRUE, 'limit' => [0, 8]]);

            $tmp = $ywDays;
            $ywDays = [];

            foreach($maxDays as $key => $value)
            {
                $tmp[$key] = $value;
                $maxYwTmp = $value;
            }

            foreach($tmp as $key => $value)
            {
                $ywDays[$value] = json_decode($key, TRUE);
            }

            asort($ywDays);
            $ywDayValues = array_values($ywDays);

            $beginYmd = $ywDayValues[0][0];
            $endYmd = $ywDayValues[count($ywDayValues) - ($maxYwTmp > $maxYw ? 2 : 1)][1];
            
            $runData = $this->load('run')->getRunDataByDay($this->uid, $beginYmd, $endYmd);

            if($runData)
            {
                $tmp = $runData;
                $runData = [];

                foreach($tmp as $rdKey => $rdVal)
                {
                    $thisYw = date('YW', strtotime($rdVal['ymd']));
                    empty($runData[$thisYw]) && $runData[$thisYw] = ['yw' => $thisYw, 'title' => $thisYw == $maxYw ? '本周' : date('n/j', strtotime($ywDays[$thisYw][0])), 'mileage' => 0];
                    $runData[$thisYw]['mileage'] += $rdVal['mileage'];
                }
            }

            foreach($ywDays as $key => $value)
            {
                if(empty($runData[$key]))
                {
                    $runData[$key] = ['yw' => $key, 'title' => $key == $maxYw ? '本周' : date('n/j', strtotime($value[0])), 'mileage' => 0];
                }
            }

            asort($runData);
            $this->result['result']['info']['is_max_yw'] = $yw == $maxYw ? 1 : 0;
            $this->result['result']['data'] = array_values($runData);
        }
    }

    // 个人按月汇总的跑步里程数据列表接口
    public function dorunDataByMonth()
    {
        if(!$this->uid)
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        else
        {
            $ym = intval(common::request('ym'));

            $maxYm = date('Ym');
            (!$ym || strlen($ym) != 6) && $ym = $maxYm;
            $ym < 201408 && $ym = 201408;

            $yms = [];
            $currentYm = $ym;

            for($i = 0; $i <= 7; $i++)
            {
                $tmpYm = date('Ym', strtotime("-{$i} month {$currentYm}01"));
                $yms[] = $tmpYm;
                $minYm = $tmpYm;
            }

            $beginYmd = $minYm . '01';
            $endYmd = date('Ymd', strtotime("-1 day +1 month {$ym}01"));

            $maxExYm = date('Y/m', strtotime("+1 day {$endYmd}"));
            $runData = $this->load('run')->getRunDataByMonth($this->uid, $beginYmd, $endYmd);
            $runData[] = ['ym' => str_replace('/', '', $maxExYm), 'title' => str_replace('/', '', $maxExYm) == $maxYm ? '本月' : $maxExYm, 'mileage' => '0.00'];

            foreach($runData as $rdKey => $rdVal)
            {
                if(empty($rdVal['title']))
                {
                    $rdVal['title'] = $rdVal['ym'] == $maxYm ? '本月' : date('Y/m', strtotime($rdVal['ym'] . '01'));
                }

                $runData[$rdVal['ym']] = $rdVal;

                unset($runData[$rdKey]);
            }

            foreach($yms as $ymKey => $ymVal)
            {
                if(empty($runData[$ymVal]))
                {
                    $runData[$ymVal] = ['ym' => date('Ym', strtotime($ymVal . '01')), 'title' => $ymVal == $maxYm ? '本月' : date('Y/m', strtotime($ymVal . '01')), 'mileage' => '0.00'];
                }
            }

            asort($runData);

            $this->result['result']['info']['is_max_ym'] = $ym == $maxYm ? 1 : 0;
            $this->result['result']['data'] = array_values($runData);
        }
    }

    // 个人指定周分析汇总数据接口
    public function dototalRunDataByWeek()
    {
        if(!$this->uid)
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        else
        {
            $yw = intval(common::request('yw'));

            $maxYw = date('YW');
            (!$yw || strlen($yw) != 6) && $yw = $maxYw;

            $totalRunData['target']['can_set_target'] = $yw == $maxYw ? 1 : 0;
            $totalRunData['target']['mileage'] = $this->load('run')->getUserSelfTarget($this->uid, $yw, 'week');
            $totalRunData['total'] = ['mileage' => 0, 'days' => 0];

            $dayData = [];

            $dayInfo = $this->redis->zrangebyscore(REDIS_PREFIX . 'Weeks', $yw, $yw);
            $dayInfo[0] = json_decode($dayInfo[0], TRUE);
            $beginYmd = $dayInfo[0][0];
            $endYmd = $dayInfo[0][1];
            $runData = $this->load('run')->getRunDataByDay($this->uid, $beginYmd, $endYmd);

            for($i = 0; $i < 7; $i++)
            {
                $dayData[date('Ymd', strtotime("+{$i} day {$beginYmd}"))] = ['title' => $this->_replaceWeekTitle(date('N', strtotime("+{$i} day {$beginYmd}"))), 'mileage' => 0];
            }

            if(!empty($runData))
            {
                $days = [];

                foreach($runData as $rdKey => $rdVal)
                {
                    $days[$rdVal['ymd']] = 0;
                    $totalRunData['total']['mileage'] += $rdVal['mileage'];
                    $dayData[$rdVal['ymd']]['mileage'] = $rdVal['mileage'];
                }

                $totalRunData['total']['days'] = count($days);
            }

            $totalRunData['data'] = array_values($dayData);
            $this->result['result'] = $totalRunData;
        }
    }

    // 个人指定月分析汇总数据接口
    public function dototalRunDataByMonth()
    {
        if(!$this->uid)
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        else
        {
            $ym = intval(common::request('ym'));

            $maxYm = date('Ym');
            (!$ym || strlen($ym) != 6) && $ym = $maxYm;

            $totalRunData['target']['can_set_target'] = $ym == $maxYm ? 1 : 0;
            $totalRunData['target']['mileage'] = $this->load('run')->getUserSelfTarget($this->uid, $ym, 'month');
            $totalRunData['total'] = ['mileage' => 0, 'days' => 0];

            $dayData = [];
            $beginYmd = $ym . '01';
            $endYmd = date('Ymd', strtotime("-1 day +1 month {$beginYmd}"));
            $runData = $this->load('run')->getRunDataByDay($this->uid, $beginYmd, $endYmd);

            for($i = $beginYmd; $i <= $endYmd; $i++)
            {
                $dayData[$i] = ['title' => date('j', strtotime($i)), 'mileage' => 0];
            }

            if(!empty($runData))
            {
                $days = [];

                foreach($runData as $rdKey => $rdVal)
                {
                    $days[$rdVal['ymd']] = 0;
                    $totalRunData['total']['mileage'] += $rdVal['mileage'];
                    $dayData[$rdVal['ymd']]['mileage'] = $rdVal['mileage'];
                }

                $totalRunData['total']['days'] = count($days);
            }

            $totalRunData['data'] = array_values($dayData);
            $this->result['result'] = $totalRunData;
        }
    }

    public function _replaceWeekTitle($week)
    {
        $weeks = ['一', '二', '三', '四', '五', '六', '日'];

        return $weeks[$week - 1];
    }
}
